package com.infore.airsupervise.ui.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.HotAnalyzeTableAdapter;
import com.infore.airsupervise.adapter.StationExpandAdapter;
import com.infore.airsupervise.app.MsgConst;
import com.infore.airsupervise.bean.PointAnalyzeE;
import com.infore.airsupervise.biz.StatisticsBiz;
import com.infore.airsupervise.biz.impl.StatisticsBizImpl;
import com.infore.airsupervise.http.OnServerResponseListener;
import com.infore.airsupervise.ui.fragment.StationTreeFragment;
import com.infore.airsupervise.utils.DateUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.inqbarna.tablefixheaders.TableFixHeaders;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * 统计模块 热力分析界面
 * Created by xiaotao on 2017/8/16.
 */

public class HotAnalyzeActivity extends BaseTitleBarActivity {
    @BindView(R.id.drawer_layout)
    DrawerLayout drawerLayout;
    @BindView(R.id.tv_time)
    EditText tvTime;
    @BindView(R.id.sel_factor)
    TextView selFactor;
    @BindView(R.id.scroll_table)
    TableFixHeaders scrollTable;
    @BindView(R.id.tv_station_name)
    TextView tvStationName;

    //选择器
    private TimePickerView timePickerView = null;
    private OptionsPickerView<String> factorPickerView = null;
    private boolean[] timeType = {true, true, false, false, false, false};
    private List<String> factorList = null;

    //表格
    private HotAnalyzeTableAdapter tableAdapter = null;

    private String[] topTitle;
    private String[] leftTitle;
    private double[][] data;

    //网络请求
    private StatisticsBiz statisticsBiz = null;
    private String time;
    private int factorType;
    private String selMN;
    private String stationName;

    //站点树 fragment
    private StationTreeFragment drawFragment = null;

    //dialog
    private SweetAlertDialog dialog = null;

    private Handler myhandler = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hot_analyze);
        ButterKnife.bind(this);
        initView();
    }

    /**
     * 初始化控件
     */
    private void initView() {
        //titleBar
        title.setText("站点热力分布");
        rightMenu.setVisibility(View.INVISIBLE);
        //时间
        time = DateUtil.getCurrentDateStr(DateUtil.dateFormatYM);
        tvTime.setText(time);
        //因子
        factorList = Arrays.asList(getResources().getStringArray(R.array.airType1));
        selFactor.setText(factorList.get(0));
        factorType = 0;
        //热力图表格
        tableAdapter = new HotAnalyzeTableAdapter(ctx);
        scrollTable.setAdapter(tableAdapter);
        myhandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                    }
                }
            }
        };
        // 提示选择站点
        //   ToastUtil.showLong(this, "请选择站点进行分析");
        scrollTable.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(!isFinishing()) {
                    getHotAnaylzeData();
                }
            }
        },500);
    }

    /**
     * 时间选择器
     */
    private void initTimePicker() {
        Calendar endSelectedDate = Calendar.getInstance();
        endSelectedDate.add(Calendar.DAY_OF_MONTH, -1);
        timePickerView = new TimePickerView.Builder(ctx, timeSelectListener)
                .setTitleText("")
                .setLabel("年", "月", "日", "点", "分", "秒")
                .setType(timeType)
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(18)
                .setRangDate(null, endSelectedDate)
                .setDate(endSelectedDate)
                .setDecorView(null)
                .setTitleText("时间选择")
                .build();
    }

    private void initFactorPicker() {
        factorPickerView = new OptionsPickerView.Builder(ctx, factorSelectListener)
                .isCenterLabel(false)
                .setTitleText("因子")
                .setDividerColor(Color.DKGRAY)
                .setDecorView(null)
                .build();
        factorPickerView.setPicker(factorList);
    }

    /**
     * 控制抽屉开关
     */
    private void drawerLayout() {
        if (!drawerLayout.isDrawerOpen(Gravity.LEFT)) {
            drawerLayout.openDrawer(Gravity.LEFT);
        } else {
            drawerLayout.closeDrawers();
        }
    }

    /**
     * 发起网络请求
     */
    private void getHotAnaylzeData() {
        if (statisticsBiz == null) {
            statisticsBiz = new StatisticsBizImpl();
        }
        dialog = new SweetAlertDialog(ctx, SweetAlertDialog.PROGRESS_TYPE)
                .setTitleText(MsgConst.HARD_LOADING);
        dialog.show();
        tableAdapter.setFactorType(factorType);
        statisticsBiz.sendHotAnalyzerequest(selMN, time, factorType, responseListener);
    }

    /**
     * 设置表格数据
     *
     * @param result
     */
    private void setHotData(List<PointAnalyzeE> result) {
        tvStationName.setText(result.get(0).getName());
        topTitle = new String[result.size()];
        for (int i = 0; i < result.size(); i++) {
            topTitle[i] = (i + 1) + ""; //日期
            List<PointAnalyzeE.VlistBean> list = result.get(i).getVlist();
            if (i == 0 && list != null && list.size() > 0) {
                leftTitle = new String[list.size()]; //时间
                data = new double[leftTitle.length][topTitle.length];
            }
            for (int j = 0; j < list.size(); j++) {
                PointAnalyzeE.VlistBean vlistBean = list.get(j);
                if (i == 0) {
                    leftTitle[j] = vlistBean.getTime().substring(11, 13);
                }
                data[j][i] = vlistBean.getValue();
            }
        }

        tableAdapter.updata(topTitle, leftTitle, data);
        scrollTable.scrollTo(0, 0);
        myhandler.sendEmptyMessage(1);
    }

    /**
     * 加减一段时间
     * @param offset
     * @return
     */
    private boolean timeOffset(int offset){
        boolean isEnd = DateUtil.compareDate(time,DateUtil.getCurrentDateStr(DateUtil.dateFormatYM),DateUtil.dateFormatYM) <= 0;
       if(!isEnd ||(offset < 0) ){
           time = DateUtil.getStringByOffset(time,DateUtil.dateFormatYM,Calendar.MONTH,offset);
           tvTime.setText(time);
       }
        return  isEnd;
    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.sel_station, R.id.iv_before, R.id.tv_time, R.id.iv_after, R.id.sel_factor})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.sel_station:
                if (drawFragment == null) {
                    drawFragment = new StationTreeFragment();
                    drawFragment.setCurType(StationExpandAdapter.RB_SELECTE);
                    drawFragment.setOnClickListener(onClicklistener);
                    getSupportFragmentManager().beginTransaction().replace(R.id.drawer_container, drawFragment).commit();
                }
                drawerLayout();
                break;
            case R.id.iv_before:
                timeOffset(-1);
                getHotAnaylzeData();
                break;
            case R.id.tv_time:
                if (timePickerView == null) {
                    initTimePicker();
                }
                timePickerView.show();
                break;
            case R.id.iv_after:
               if(timeOffset(1)){
                   ToastUtil.showShort(ctx,"不能超过当前日期");
               }else {
                   getHotAnaylzeData();
               }
                break;
            case R.id.sel_factor:
                if (factorPickerView == null) {
                    initFactorPicker();
                }
                factorPickerView.show();
                break;
        }
    }

    /**
     * 站点树点击事件
     */
    private StationTreeFragment.OnClickListener onClicklistener = new StationTreeFragment.OnClickListener() {
        @Override
        public void onConfirmClick(String mn) {

        }

        @Override
        public void onConfirmClick(String mn, String name) {
            selMN = mn;
            stationName = name;
            getHotAnaylzeData();
            drawerLayout();
        }

        @Override
        public void onCancelClick() {
            drawerLayout();
        }
    };

    /**
     * 时间选择回调
     */
    private TimePickerView.OnTimeSelectListener timeSelectListener = new TimePickerView.OnTimeSelectListener() {
        @Override
        public void onTimeSelect(Date date, View v) {
            time = DateUtil.getStringByFormat(date, DateUtil.dateFormatYM);
            tvTime.setText(time);
            getHotAnaylzeData();
        }
    };

    /**
     * 因子选择回调
     */
    private OptionsPickerView.OnOptionsSelectListener factorSelectListener = new OptionsPickerView.OnOptionsSelectListener() {
        @Override
        public void onOptionsSelect(int options1, int options2, int options3, View v) {
            selFactor.setText(factorList.get(options1));
            factorType = options1;
            getHotAnaylzeData();
        }
    };

    /**
     * 网络请求回调
     */
    private OnServerResponseListener<List<PointAnalyzeE>> responseListener = new OnServerResponseListener<List<PointAnalyzeE>>() {
        @Override
        public void onSucceed(List<PointAnalyzeE> result, String desc) {
            if (result == null || result.size() <= 0) {
                return;
            }
            setHotData(result);
        }

        @Override
        public void onFailed(int errorCode, String title, String desc) {
            dialog.dismiss();
        }
    };
}
